//
//  HRChangeBackImageViewController.m
//  Hear
//
//  Created by mac on 2017/4/12.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRChangeBackImageViewController.h"
#import "OSSImageUploader.h"
#import "UzysImagePickerController.h"
#import "HRShowPowerControlView.h"
#import "HRContactsManager.h"
#import "HRLocationViewModel.h"
#import "YContactObject.h"
#import "HRBackGroundImageRemendView.h"
@interface HRChangeBackImageViewController ()<UzysImagePickerControllerDelegate>
@property (nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic,strong) UIButton *submitBtn;
@property(nonatomic, strong)UIButton  *bigImageView;
@property(nonatomic, strong)NSMutableArray *selectImageArr;
@property(nonatomic, strong)UIButton *tempButton;
@property (nonatomic, strong)HRLocationViewModel *locationViewModel;
@property(nonatomic, strong)NSMutableArray *tempImageArr;

@end

@implementation HRChangeBackImageViewController

#pragma mark - Get and Set
- (HRLocationViewModel *)locationViewModel{
    if (_locationViewModel == nil) {
        _locationViewModel = [[HRLocationViewModel alloc] init];
    }
    return _locationViewModel;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"更改背景";
    
    self.selectImageArr = [NSMutableArray array];
    self.tempImageArr = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupView];
    
    WeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (![[HRContactsManager shareInstance]hasOpenContactsPower]){
            if (ISOPENTADDRESSBOOK)return;
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isShowRemendOpenAddressBook"];

            NSMutableArray *mobileNumArr = [NSMutableArray array];
            [[HRContactsManager shareInstance] requestContactsComplete:^(NSArray<YContactObject *> * _Nonnull contacts) {
                
                //开始赋值
                for (YContactObject *object in contacts) {
                    YContactPhoneObject *phontObject = [object.phoneObject firstObject];
                    NSString *mobileNumStr = [phontObject.phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    if ([mobileNumStr isMobileNumber]){
                        DDLog(@"phoneNumber========================%@",mobileNumStr);
                        [mobileNumArr addObject:mobileNumStr];
                    }
                    
                }
                [weakSelf postSaveUserContacts:[mobileNumArr jsonStringEncoded]];
            }];
        }
    });
}

- (void)postSaveUserContacts:(NSString *)MobileList{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"MobileList"] = MobileList;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    [self.locationViewModel postSaveUserContacts:paramDict isSeccess:^(BOOL isSeccess) {
        [MBProgressHUD hideHUDForView:WINDOW animated:YES];
    }];
}

- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}

- (void)setupView{
    
    UIButton *enterButton = [UIButton buttonWithType:0];
    enterButton.size = CGSizeMake(40, 30);
    [enterButton setTitle:@"确定" forState:0];
    [enterButton addTarget:self action:@selector(submitBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:enterButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.scrollView];
    
    
    CGFloat pading = 7;
    CGFloat smallPhontWidth = (kFullWidth-pading*2)/3;
    
    CGFloat bigPhontWidth = kFullWidth-pading-smallPhontWidth;
    
    self.bigImageView = [UIButton buttonWithType:0];
    self.bigImageView.frame = CGRectMake(0, 20, bigPhontWidth, bigPhontWidth);
    [self.bigImageView addTarget:self action:@selector(imageViewClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:self.bigImageView];
    [self.bigImageView setBackgroundImage:[UIImage imageNamed:@"圆角矩形-40-拷贝"] forState:0];
    self.bigImageView.tag = 0;

    
    if (self.imageArr.count){
        [self.tempImageArr addObjectsFromArray:self.imageArr];
        [self.selectImageArr addObjectsFromArray:self.imageArr];
        [self.bigImageView setImageWithURL:[NSURL URLWithString:[self.imageArr firstObject]] forState:0 placeholder:nil];
    }
    
    for (int i =0; i < 5; i++) {
        UIButton *button = [UIButton buttonWithType:0];
        button.tag = i+1;
        [button addTarget:self action:@selector(imageViewClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:button];
        if (i < 3){
            button.frame = CGRectMake(self.bigImageView.right+pading, self.bigImageView.top+i*(smallPhontWidth+pading), smallPhontWidth, smallPhontWidth);
            if (self.imageArr.count>(i+1)){
                [button setImageWithURL:[NSURL URLWithString:self.imageArr[i+1]] forState:0 placeholder:nil];
            }else{
                [button setBackgroundImage:[UIImage imageNamed:@"圆角矩形-40-拷贝"] forState:0];
            }
            
        }else{
            button.frame = CGRectMake((i-3)*(smallPhontWidth+pading), self.bigImageView.bottom+pading, smallPhontWidth, smallPhontWidth);
            if (self.imageArr.count>(i+1)){
                [button setImageWithURL:[NSURL URLWithString:self.imageArr[i+1]] forState:0 placeholder:nil];
            }else{
                [button setBackgroundImage:[UIImage imageNamed:@"圆角矩形-40-拷贝"] forState:0];
            }
        }
    }
    
    
    
    UILabel *descLabel = [UILabel new];
    descLabel.textAlignment = 1;
    descLabel.numberOfLines = 0;
    descLabel.frame = CGRectMake(20, self.bigImageView.bottom+smallPhontWidth+pading+30, kFullWidth-40, 100);
    descLabel.text = @"";
    descLabel.font = CustomUIFont(14);
    descLabel.textColor =FirstTextColor;
    [self.scrollView  addSubview:descLabel];
    descLabel.text = @"添加1-6张展现你自己的照片，风格品味、兴趣爱好会让你更受欢迎。";
}








- (void)imageViewClick:(UIButton *)button{

    self.tempButton = button;
    WeakSelf
    [HRBackGroundImageRemendView showBackGroundImageRemendView:^(int selectIndex) {
        if (selectIndex == 0){
            UzysImagePickerController * UzysImageP = [[UzysImagePickerController alloc] init];
            [UzysImageP showInViewContrller:weakSelf maxCount:1 delegate:weakSelf];
        }else{
            if (!weakSelf.tempImageArr.count || !weakSelf.selectImageArr.count){
                return ;
            }
            if (weakSelf.tempButton.tag >= weakSelf.tempImageArr.count){
                [weakSelf.selectImageArr removeObject:weakSelf.tempButton.currentImage];
            }else{
                id imageObject = [weakSelf.tempImageArr objectAtIndex:weakSelf.tempButton.tag];
                [weakSelf.selectImageArr removeObject:imageObject];
            }
            
            
            [weakSelf.tempImageArr removeAllObjects];
            [weakSelf.tempImageArr addObjectsFromArray:weakSelf.selectImageArr];
            
            [weakSelf.tempButton setImage:nil forState:0];
            [weakSelf.tempButton setBackgroundImage:[UIImage imageNamed:@"圆角矩形-40-拷贝"] forState:0];
        }
    } andIsCancel:(!button.currentImage)];//
    
    
}

- (void)UzysImagePickerDidFinishWithImages:(NSArray *)imageArray{
    
    [self.tempButton setImage:[imageArray firstObject] forState:0];
    
    if (self.tempButton.tag < self.selectImageArr.count){
        [self.selectImageArr removeObjectAtIndex:self.tempButton.tag];
        [self.tempImageArr removeObjectAtIndex:self.tempButton.tag];
    }
    
    [self.selectImageArr addObject:[imageArray firstObject]];
    [self.tempImageArr addObject:[imageArray firstObject]];
}



- (void)submitBtnClicked{
    
    NSMutableArray *formatImageArr = [NSMutableArray array];
    
    NSMutableArray *imageArr = [NSMutableArray array];

    for (id objc in self.selectImageArr) {
        if ([objc isKindOfClass:[NSString class]]){
            if ([objc hasPrefix:@"http"]){
                [formatImageArr addObject:objc];
            }
        }else{
            [imageArr addObject:objc];
        }
    }
 
    if (imageArr.count){
        [OSSImageUploader asyncUploadImages:imageArr complete:^(NSArray<NSString *> *names, UploadImageState state) {
            if (state == UploadImageFailed) return ;
            
            for (NSString *url in names)
            {
                [formatImageArr addObject:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,url]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSError *error = nil;
                NSString *imageJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:formatImageArr options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];
                
                
                [self putToServer:imageJson];
            });
        }];
    }else if (formatImageArr.count){
        NSError *error = nil;
        NSString *imageJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:formatImageArr options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];
        
        
        [self putToServer:imageJson];
    }else{
        [MBProgressHUD showMessage:@"照片墙需至少保留一张，请用新照片替换" finishBlock:nil];
    }
}


- (void)putToServer:(NSString *)jsonImage{
    YTKApi *api = [YTKApi apiPutWithUrl:@"UserInfo/Put_UpdateUserInfo" para:@{@"LocalId":USERID,@"Value":jsonImage,@"UserUpdateType":@"10"}];
    WeakSelf
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseObject;
            [[NSUserDefaults standardUserDefaults] setObject:dict[@"BodyContent"] forKey:@"userInfo"];

            [[NSUserDefaults standardUserDefaults] setObject:jsonImage forKey:@"UserCoverPicture"];
            
          dispatch_async(dispatch_get_main_queue(), ^{
              [MBProgressHUD showMessage:@"更改成功" finishBlock:nil];
              [self.navigationController popViewControllerAnimated:YES];
              if (weakSelf.changeImageBlock){
                  weakSelf.changeImageBlock();
              }
          });
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        }];
    }];
}



- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 识别人脸
- (BOOL)faceDetectWithImage:(UIImage *)image {
    // 图像识别能力：可以在CIDetectorAccuracyHigh(较强的处理能力)与CIDetectorAccuracyLow(较弱的处理能力)中选择
    NSDictionary *opts = [NSDictionary dictionaryWithObject:
                          CIDetectorAccuracyLow forKey:CIDetectorAccuracy];
    // 将图像转换为CIImage
    CIImage *faceImage = [CIImage imageWithCGImage:image.CGImage];
    CIDetector *faceDetector=[CIDetector detectorOfType:CIDetectorTypeFace context:nil options:opts];
    // 识别出人脸数组
    NSArray *features = [faceDetector featuresInImage:faceImage];
    // 得到图片的尺寸
    CGSize inputImageSize = [faceImage extent].size;
    //将image沿y轴对称
    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, -1);
    //将图片上移
    transform = CGAffineTransformTranslate(transform, 0, -inputImageSize.height);
    
    // 取出所有人脸
    for (CIFaceFeature *faceFeature in features){
        //获取人脸的frame
        //        CGRect faceViewBounds = CGRectApplyAffineTransform(faceFeature.bounds, transform);
        //        CGSize viewSize = _imageView.bounds.size;
        //        CGFloat scale = MIN(viewSize.width / inputImageSize.width,
        //                            viewSize.height / inputImageSize.height);
        //        CGFloat offsetX = (viewSize.width - inputImageSize.width * scale) / 2;
        //        CGFloat offsetY = (viewSize.height - inputImageSize.height * scale) / 2;
        //        // 缩放
        //        CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scale, scale);
        //        // 修正
        //        faceViewBounds = CGRectApplyAffineTransform(faceViewBounds,scaleTransform);
        //        faceViewBounds.origin.x += offsetX;
        //        faceViewBounds.origin.y += offsetY;
        //
        //        //描绘人脸区域
        //        UIView* faceView = [[UIView alloc] initWithFrame:faceViewBounds];
        //        faceView.layer.borderWidth = 2;
        //        faceView.layer.borderColor = [[UIColor redColor] CGColor];
        //        [_imageView addSubview:faceView];
        
        // 判断是否有左眼位置
        if(faceFeature.hasLeftEyePosition){
            DDLog(@"======================有左眼");
            
        }
        // 判断是否有右眼位置
        if(faceFeature.hasRightEyePosition){
            DDLog(@"======================有右眼");
        }
        // 判断是否有嘴位置
        if(faceFeature.hasMouthPosition){
            DDLog(@"======================有嘴");
        }
        
        return YES;
        
    }
    return NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
